import 'package:amway_superapp_creator_plugin/analysis/zhuge_edit.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/comm_tip_dialog.dart';
import 'package:amway_superapp_creator_plugin/dialog/loading_dialog.dart';
import 'package:amway_superapp_creator_plugin/models/create_user_info_model.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/utils/image_pickasset_util.dart';
import 'package:amway_superapp_creator_plugin/utils/throttle.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/cover/set_cover_model.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:amway_superapp_creator_plugin/widget/back_button.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:page_view_indicators/circle_page_indicator.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'cover_image_item.dart';

class SetCoverView extends StatelessWidget {
  var scrollController = new ScrollController();
  List<ImagesBean> covers;
  var amwayAda;

  SetCoverView({this.covers, this.amwayAda});

  @override
  Widget build(BuildContext context) {
    ZhugeEditAnalysis.editPage(EditPageType.editCover);
    return BaseView(
      model: SetCoverModel(api: Provider.of(context)),
      onModelReady: (model) async {
        model.initUserCovers(covers);
        model.initDatas(amwayAda);
        model.initAlbumSelSize();
      },
      builder: (context, model, child) => WillPopScope(
          child: Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.white,
              leading: BackButtion(
                onTap: () {
                  model.setFirstJoin(amwayAda: amwayAda, value: false);
                  if (model.checkImagesDatas.length <= 0) {
                    ToastUtils.showShortToast('至少选中1张封面图');
                    return;
                  } else {
                    if (!model.checkUpdateState()) {
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (_) {
                            return CommTipDialog(
                              content: '返回上一步会丢失当前信息，是否返回？',
                              confirmText: "知道了",
                              closeText: '取消',
                              confirmCallback: () {
                                Application.router.pop(context);
                              },
                              dismissCallback: () {},
                            );
                          });
                      return;
                    } else {
                      Application.router.pop(context);
                    }
                  }
                },
              ),
              title: Text(
                '编辑封面',
                style: TextStyle(
                  color: ColorsConfig.c_2c2c2c,
                  fontSize: ScreenUtil().setSp(20),
                ),
              ),
              centerTitle: true,
            ),
            body: Container(
              color: Colors.white,
              child: Column(
                children: [
                  buildTopTip(context, model),
                  Expanded(
                    child: Container(
                      child: buildTopBody(context, model),
                    ),
                    flex: 1,
                  ),
                ],
              ),
            ),
            bottomNavigationBar: builderBottomButton(context, model),
          ),
          onWillPop: () {
            model.setFirstJoin(amwayAda: amwayAda, value: false);
            if (model.checkImagesDatas.length <= 0) {
              ToastUtils.showShortToast('至少选中1张封面图');
            } else {
              if (!model.checkUpdateState()) {
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (_) {
                      return CommTipDialog(
                        content: '返回上一步会丢失当前信息，是否返回？',
                        confirmText: "知道了",
                        closeText: "取消",
                        confirmCallback: () {
                          Navigator.of(context).pop(true);
                        },
                        dismissCallback: () {},
                      );
                    });
              } else {
                Application.router.pop(context);
              }
            }
          }),
    );
  }

  Widget buildTopBody(BuildContext context, SetCoverModel model) {
    return SingleChildScrollView(
      child: Container(
        color: Colors.white,
        child: Column(
          children: [
            Container(
              color: Colors.white,
              child: builderViewPage(context, model),
            ),
            _buildPageViewIndicator(context, model),
            _builderTips(context, model),
            builderBottomImages(context, model),
          ],
        ),
      ),
    );
  }

  Widget buildTopTip(BuildContext context, SetCoverModel model) {
    return !model.isDayFirstJoin
        ? Container()
        : Center(
            child: Container(
              width: ScreenUtil().setWidth(220),
              margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
              padding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(17),
                  right: ScreenUtil().setWidth(17),
                  top: ScreenUtil().setHeight(10),
                  bottom: ScreenUtil().setHeight(10)),
              decoration: BoxDecoration(
                color: ColorsConfig.c_2c2c2c,
                borderRadius: BorderRadius.all(Radius.circular(25)),
              ),
              child: Row(
                children: [
                  Text(
                    '请上传您最具风采的封面照',
                    style: TextStyle(
                        color: Colors.white, fontSize: ScreenUtil().setSp(14)),
                  ),
                  InkWell(
                    child: Container(
                      child: Icon(
                        Icons.close,
                        color: Colors.grey,
                        size: 10,
                      ),
                    ),
                    onTap: () {
                      model.setFirstJoin(value: false, amwayAda: amwayAda);
                    },
                  )
                ],
              ),
            ),
          );
  }

  @override
  Widget buildBigImageLoading(
      BuildContext context, AssetEntity entity, Color themeColor) {
    return Center(
      child: Container(
        width: 50.0,
        height: 50.0,
        child: CupertinoActivityIndicator(
          radius: 25.0,
        ),
      ),
    );
  }

  @override
  Widget buildPreviewLoading(
      BuildContext context, AssetEntity entity, Color themeColor) {
    return Center(
      child: Container(
        width: 50.0,
        height: 50.0,
        child: CupertinoActivityIndicator(
          radius: 25.0,
        ),
      ),
    );
  }
}

Widget _builderTips(BuildContext context, SetCoverModel model) {
  return model.checkImagesDatas.length > 1
      ? Container(
          width: double.infinity,
          color: Colors.white,
          child: Text(
            '可以通过长按拖拽方式调整展示顺序',
            textAlign: TextAlign.center,
            style: TextStyle(
                fontSize: ScreenUtil().setSp(12),
                color: ColorsConfig.c_80000000),
          ),
        )
      : Container();
}

Widget builderViewPage(BuildContext context, SetCoverModel model) {
  return Container(
    height: ScreenUtil().setHeight(500),
    child: model.checkImagesDatas.length > 0
        ? PageView.builder(
            onPageChanged: (index) {
              _currentPageNotifier.value = index;
            },
            controller: _pageController,
            itemCount: model.checkImagesDatas.length,
            itemBuilder: (BuildContext context, int index) {
              return builderViewPageItem(context, model, index);
            })
        : builderNoSelImagesItem(context, model),
  );
}

final _pageController = PageController(viewportFraction: 0.8);
final _currentPageNotifier = ValueNotifier<int>(0);
//指示器
Widget _buildPageViewIndicator(BuildContext context, SetCoverModel model) {
  return model.checkImagesDatas.length > 1
      ? Container(
          width: double.infinity,
          color: Colors.white,
          padding: EdgeInsets.only(
              top: ScreenUtil().setHeight(12),
              bottom: ScreenUtil().setHeight(12)),
          child: CirclePageIndicator(
            currentPageNotifier: _currentPageNotifier,
            itemCount: model.checkImagesDatas.length,
          ))
      : Container();
}

//图片Item
Widget builderViewPageItem(
    BuildContext context, SetCoverModel model, int index) {
  return Container(
    padding: EdgeInsets.only(
        top: ScreenUtil().setHeight(20),
        left: ScreenUtil().setWidth(12),
        right: ScreenUtil().setWidth(12)),
    child: Card(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadiusDirectional.circular(18)),
      clipBehavior: Clip.antiAlias,
      child: Stack(
        fit: StackFit.expand,
        children: [
          model.checkImagesDatas[index].officialFlag == "YES"
              ? Image.network(
                  model.checkImagesDatas[index].data,
                  fit: BoxFit.cover,
                )
              : null == model.checkImagesDatas[index].assetEntity
                  ? Image.network(
                      model.checkImagesDatas[index].data,
                      fit: BoxFit.cover,
                    )
                  : CoverImageItem(
                      entity: model.checkImagesDatas[index].assetEntity,
                    ),
          Align(
            alignment: Alignment.topRight,
            child: InkWell(
              onTap: () {
                /*if (model.checkImagesDatas.length <= 1) {
                    ToastUtils.showShortToast('最少保留一个');
                  } else {*/
                model.removeSelImage(model.checkImagesDatas[index]);
                //}
              },
              child: Container(
                padding: EdgeInsets.only(
                    left: ScreenUtil().setWidth(10),
                    bottom: ScreenUtil().setHeight(10),
                    top: ScreenUtil().setHeight(10),
                    right: ScreenUtil().setWidth(10)),
                child: Container(
                  width: ScreenUtil().setWidth(24),
                  height: ScreenUtil().setHeight(24),
                  child: Image.asset(
                    "picture/icon_del.png",
                    package: 'amway_superapp_creator_plugin',
                  ),
                ),
              ),
            ),
          ),
          model.checkitemIsFaild(index)
              ? Align(
                  alignment: Alignment.center,
                  child: Image.asset(
                    "picture/icon_audit_nopass.png",
                    package: 'amway_superapp_creator_plugin',
                  ),
                )
              : Container(),
        ],
      ),
    ),
  );
}

Widget builderNoSelImagesItem(BuildContext context, SetCoverModel model) {
  return Center(
      child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Image.asset(
        "picture/img_no_sel.png",
        package: "amway_superapp_creator_plugin",
        fit: BoxFit.cover,
      ),
      Text(
        "当前还没有添加任何封面图片哦",
        style: TextStyle(
          fontSize: ScreenUtil().setSp(12),
          color: ColorsConfig.c_4D2C2C2C,
        ),
      ),
    ],
  ));
}

Widget builderBottomImages(BuildContext context, SetCoverModel model) {
  return Container(
    margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
    color: Colors.white,
    width: double.infinity,
    height: ScreenUtil().setHeight(230),
    child: SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: [
          _builderBottomItemAlbum(context, "本地相册", model),
          Container(
            child: ListView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                scrollDirection: Axis.horizontal,
                itemCount: model.datas.length,
                itemBuilder: (context, index) {
                  return _builderBottomItemNetCover(
                      context, "封面图片素材", model, index);
                }),
          )
        ],
      ),
    ),
  );
}

Widget builderBottomButton(BuildContext context, SetCoverModel model) {
  return Container(
    padding: EdgeInsets.all(16),
    width: double.infinity,
    color: Colors.white,
    child: FlatButton(
      onPressed: throttle(() async {
        await Future.delayed(Duration(milliseconds: 1000));

        if (model.checkImagesDatas.length <= 0) {
          ToastUtils.showShortToast('至少选中1张封面图');
          return;
        }
        if(model.checkUpdateState()){
          Application.router.pop(context, model.checkImagesDatas);
          return;
        }


        showDialog(
          context: context,
          builder: (ctx) {
            return LoadingDialog(
              canceledOnTouchOutside: false,
              tipMsg: '正在上传中',
            );
          },
        );
        model.uploadMultiImages(model.checkImagesDatas, (data) {
          Application.router.pop(context);

          Application.router.pop(context, data);
        });
      }),
      color: model.checkImagesDatas.length > 0
          ? ColorsConfig.c_396E75
          : Colors.grey,
      disabledColor: model.checkImagesDatas.length <= 0
          ? Colors.grey
          : ColorsConfig.c_396E75,
      height: ScreenUtil().setHeight(50),
      shape: StadiumBorder(),
      child: Text('完成(${model.checkImagesDatas.length}/3)',
          style: TextStyle(color: Colors.white)),
    ),
  );
}

Widget _builderBottomItemAlbum(
    BuildContext context, String itemName, SetCoverModel model) {
  return InkWell(
    onTap: throttle(() async {
      await Future.delayed(Duration(milliseconds: 1000));

      if (model.checkImagesDatas.length < 3) {
        pickAsset(context, RequestType.image,
                maxAssetsCount: 3,
                length: model.isAuditfailed
                    ? (model.checkImagesDatas.length - model.failednum)
                    : model.checkImagesDatas.length)
            .then((value) {
          if (value != null) {
            model.removefailure();
            model.addLocaDatas(value);
          }
        });
      } else {
        if (model.failednum > 0) {
          pickAsset(context, RequestType.image,
                  maxAssetsCount: 3,
                  length: model.isAuditfailed
                      ? (model.checkImagesDatas.length - model.failednum)
                      : model.checkImagesDatas.length)
              .then((value) {
            if (value != null) {
              model.removefailure();
              model.addLocaDatas(value);
            }
          });
        } else {
          ToastUtils.showShortToast("最多只能选择3张封面图哦");
        }
      }
      ZhugeEditAnalysis.editThumbnailClickPage("编辑封面页", true);
    }),
    child: Container(
      padding: EdgeInsets.only(
        left: ScreenUtil().setWidth(19),
        right: ScreenUtil().setWidth(15),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            itemName,
            textAlign: TextAlign.start,
            style: TextStyle(
                color: ColorsConfig.c_80111111,
                fontSize: ScreenUtil().setSp(12)),
          ),
          Container(
            width: ScreenUtil().setWidth(109),
            height: ScreenUtil().setWidth(109),
            margin: EdgeInsets.only(top: ScreenUtil().setHeight(8)),
            child: Stack(
              children: [
                Container(
                  width: ScreenUtil().setWidth(109),
                  height: ScreenUtil().setWidth(109),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20),
                    child: model.selAlbumCount == 0
                        ? Image.asset(
                            "picture/img_local_album.png",
                            fit: BoxFit.fill,
                            package: 'amway_superapp_creator_plugin',
                          )
                        : model.assetEntity == null
                            ? Image.asset(
                                "picture/img_local_album.png",
                                package: 'amway_superapp_creator_plugin',
                              )
                            : CoverImageItem(
                                entity: model.assetEntity,
                              ),
                  ),
                ),
                model.isAuditfailed
                    ? Align(
                        alignment: Alignment.topRight,
                        child: Container(
                          margin: EdgeInsets.only(right: 10, top: 10),
                          width: ScreenUtil().setWidth(10),
                          height: ScreenUtil().setWidth(10),
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(25.0)),
                              color: Colors.red),
                        ),
                      )
                    : model.selAlbumCount > 0
                        ? Align(
                            alignment: Alignment.topRight,
                            child: Padding(
                              padding: EdgeInsets.only(
                                  right: ScreenUtil().setWidth(10),
                                  top: ScreenUtil().setHeight(8)),
                              child: Container(
                                width: ScreenUtil().setWidth(22),
                                height: ScreenUtil().setWidth(22),
                                decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(25.0)),
                                    color: ColorsConfig.c_396E75),
                                child: Center(
                                  child: Text(
                                    model.selAlbumCount.toString(),
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: ScreenUtil().setSp(12)),
                                  ),
                                ),
                              ),
                            ))
                        : Container()
              ],
            ),
          )
        ],
      ),
    ),
  );
}

Widget _builderBottomItemNetCover(
    BuildContext context, String itemName, SetCoverModel model, int index) {
  return Container(
    padding: EdgeInsets.only(
      left: ScreenUtil().setWidth(12),
      bottom: ScreenUtil().setHeight(20),
    ),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        index == 0
            ? Text(
                itemName,
                textAlign: TextAlign.start,
                style: TextStyle(
                    color: ColorsConfig.c_80111111,
                    fontSize: ScreenUtil().setSp(12)),
              )
            : Text(""),
        Container(
          width: ScreenUtil().setWidth(109),
          height: ScreenUtil().setWidth(109),
          margin: EdgeInsets.only(top: ScreenUtil().setHeight(8)),
          child: InkWell(
            onTap: () {
              model.checkSelImageSource(model.datas[index]);
              ZhugeEditAnalysis.editThumbnailClickPage("编辑封面页", false);
            },
            child: Stack(
              children: [
                Container(
                  width: ScreenUtil().setWidth(109),
                  height: ScreenUtil().setWidth(109),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20),
                    child: model.datas[index].officialFlag == "YES"
                        ? Image.network(model.datas[index].data,
                            fit: BoxFit.cover)
                        : CoverImageItem(
                            entity: model.datas[index].assetEntity),
                  ),
                ),
                Align(
                  alignment: Alignment.topRight,
                  child: Padding(
                    padding: EdgeInsets.only(
                        right: ScreenUtil().setWidth(10),
                        top: ScreenUtil().setWidth(10)),
                    child: Stack(
                      children: [
                        Icon(
                          Icons.circle,
                          color: Colors.white,
                          size: ScreenUtil().setWidth(22),
                        ),
                        Icon(
                          model.initChecks(index)
                              ? Icons.check_circle
                              : Icons.circle,
                          color: model.initChecks(index)
                              ? ColorsConfig.c_396E75
                              : Colors.grey,
                          size: ScreenUtil().setWidth(22),
                        ),
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        )
      ],
    ),
  );
}
